package index

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"gluenet/pkg/apis"
)

type PageIndex struct {
	IdMap map[string]interface{} `json:"id_map" yaml:"id_map" xorm:"id_map"`
	List  []interface{}          `json:"list" yaml:"list" xorm:"list"`
}

func IndexAdd(ctx *apis.GlueContext) {
	id := ctx.WebContext.URLParam("id")
	name := ctx.WebContext.URLParam("name")
	chart := ctx.WebContext.URLParam("chart")
	args := ctx.WebContext.URLParam("args")

	var data string
	if err := ctx.DataBase.GetIndex(&data); err != nil {
		ctx.Logger.Errorf("query error %v", err)
		ctx.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("query error:%v", err), nil))
		return
	}

	var indexLine = []interface{}{
		id,
		name,
		chart,
		args,
	}

	bts, _ := json.Marshal(indexLine)
	d := md5.Sum(bts)
	sid := hex.EncodeToString(d[:])

	var indexData PageIndex
	if err := json.Unmarshal([]byte(data), &indexData); err != nil {
		ctx.Logger.Errorf("unmarshall error %v", err)
		ctx.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("unmarshall error:%v", err), nil))
		return
	}

	if _, ok := indexData.IdMap[sid]; ok {
		ctx.Logger.Errorf("page is exist")
		ctx.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("page is exist"), nil))
		return
	}

	indexData.IdMap[sid] = indexLine
	indexData.List = append(indexData.List, indexLine)
	bts2, _ := json.Marshal(indexData)
	if err := ctx.DataBase.PutIndex(string(bts2)); err != nil {
		ctx.Logger.Errorf("query error %v", err)
		ctx.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("query error:%v", err), nil))
		return
	}

	ctx.WebContext.JSON(apis.ResponseOK(nil))
}
